package example;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: fzykd
 * Date: 2022-10-16
 * Time: 20:21
 */
class MyBlockingQueue{
    //先写一个循环队列  在是实现阻塞
    private int[] data = new int[10000];
    private int size = 0;
    private int head = 0;
    private int tail = 0;

    //专门的锁对象
    private Object locker = new Object();

    //入队
    public void put(int value) throws InterruptedException {
       synchronized (locker){
           if (size == data.length){
               locker.wait();
           }
           data[tail] = value;
           tail++;
           if (tail>= data.length){
               tail = 0;
           }
           size++;
           locker.notify();
       }
    }
    //出队
    public Integer take() throws InterruptedException {
        synchronized (locker){
            if (size == 0){
                locker.wait();
            }
            int ret = data[head];
            head++;
            if (head >= data.length){
                head = 0;
            }
            size--;
            locker.notify();
            return ret;
        }
    }
}

//实现一个阻塞队列
public class TestDemo {
    private static MyBlockingQueue queue = new MyBlockingQueue();

    public static void main(String[] args) {
        //实现一个生产者消费者模型
        Thread producer = new Thread(() -> {
            int num = 0;
            while (true) {
                try {
                    System.out.println("生产了: " + num);
                    queue.put(num);
                    num++;
                    // 当生产者生产的慢一些的时候, 消费者就得跟着生产者的步伐走.
                    // Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        producer.start();


        Thread customer = new Thread(() -> {
            while (true) {
                try {
                    int num = queue.take();
                    System.out.println("消费了: " + num);
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        customer.start();
    }
}
